﻿Imports System.Net
Imports System.IO
Imports System.Data.OleDb
Imports System.Web.Security
Imports Samples.AccessProviders
Imports System.Web
Imports LecturerAppointmentSystem
Imports LecturerAppointmentSystem.UserDetails

Public Class callback
    Inherits System.Web.UI.Page

    Public Const FaceBookAppKey As String = "255426577807393"
    Dim facebookName As String = ""
    Dim firstName As String = ""
    Dim lastName As String = ""
    Dim facebookId As String = ""
    Dim email As String = ""
    Dim json__1 As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'If user is not logged into facebook and tries to access the app
        If Request.Cookies("fbs_" + FaceBookAppKey) Is Nothing Then
            Response.Redirect("Login.aspx")
        Else
            Dim cookie As String = Request.Cookies("fbs_" + FaceBookAppKey).Value
            cookie = cookie.Replace("""", "")
            Dim facebookValues As NameValueCollection = HttpUtility.ParseQueryString(cookie)
            json__1 = GetFacebookUserJSON(facebookValues("uid"), facebookValues("access_token"))
            Dim jsonHash As Hashtable = DirectCast(JSON.JsonDecode(json__1), Hashtable)
            facebookName = TryCast(jsonHash("name"), String)
            firstName = TryCast(jsonHash("first_name"), String)
            lastName = TryCast(jsonHash("last_name"), String)
            facebookId = TryCast(jsonHash("id"), String)
            email = TryCast(jsonHash("email"), String)
            LoginUser()
        End If
    End Sub

    Sub LoginUser()
        'Dim currentUserPassword As String = ""
        Dim allTheUsers As Array = getAllUsersByFacebookId()
        If doesUserExist(allTheUsers, facebookId) = True Then
            Dim userName As String = getUserName(allTheUsers, facebookId)
            Dim usr As MembershipUser = Membership.GetUser(userName)
            If Not usr.IsApproved Then
                Response.Redirect("Login.aspx?notApproved=True")
            ElseIf usr.IsLockedOut Then
                Response.Redirect("Login.aspx?isLockedOut=True")
            ElseIf usr.IsApproved AndAlso Not usr.IsLockedOut Then
                FormsAuthentication.RedirectFromLoginPage(userName, True)
                Response.Redirect("Default.aspx?fbid=" & facebookId)
            End If
        Else
            'the user is a new user, redirect to the register page
            Response.Redirect("Register.aspx?fbid=" & facebookId)
        End If
    End Sub
End Class